<template>
  <div class="write"  style="height: 100%;overflow-y: auto">
    <!-- form 表单-->
    <Write ref="write" :senderEmail="form.senderEmail" :emailSubject="form.emailSubject" @review="review"
           @getSendEmail="getSendEmail" @getCancel="getCancel" :isLoading="isLoading"
           @getInfoWrite="getInfoWrite" @toApproval="toApproval"></Write>
    <!-- 编辑器操作-->
    <MakeBtn ref="makeBtn" @getInfoMake="getInfoMake"></MakeBtn>
    <!--发件人信息-->
    <div class="info">
      <h1>发件人: {{form.senderNickName}}</h1>
      <el-checkbox-group v-model="checkList">
        <el-checkbox label="紧急"></el-checkbox>
        <el-checkbox label="回执"></el-checkbox>
        <el-checkbox label="定时发送"></el-checkbox>
        <el-checkbox label="追踪邮件"></el-checkbox>
      </el-checkbox-group>
    </div>
    <!--操作按钮-->
    <div class="make-btn">
      <el-button class="active" @click="$refs.write.sendEmail('')" :disabled="isLoading"><i class="icon-fasong iconfont"></i>发送</el-button>
      <el-button @click="$refs.write.toApproval()" :disabled="isLoading">提交审批</el-button>
      <el-button @click="$refs.write.sendEmail(2)" :disabled="isLoading">{{content?'保存至草稿箱':'存草稿'}}</el-button>
    </div>
    <DialogTargetTime ref="dialogTargetTime" @getRightTime="getRightTime"></DialogTargetTime>
    <DialogApproval ref="dialogApproval" @reset="reset"></DialogApproval>
  </div>
</template>
<script>
    import Write from '@/components/mail/write/Write'
    import MakeBtn from '@/components/mail/write/MakeBtn'
    import {sendEmail} from "@/api/mail/write";
    import DialogApproval from '@/components/mail/DialogApproval'
    import {dealStr} from '@/util/util'
    import {mapState, mapGetters} from 'vuex'
    import DialogTargetTime from '@/components/mail/DialogTargetTime'

    export default {
        name: 'write',
        props: {
            targetEmail: {
                default: ''
            }
        },
        components: {Write, MakeBtn, DialogTargetTime, DialogApproval},
        data() {
            return {
                form: {
                    addresseeEmail: [],//收件人邮箱数组
                    emailCarbonCopy: [],//抄送数组
                    emailSecretDelivery: [],//密送数组
                    emailHtmlpicList: [],//附件列表
                    emailSubject: '',//主题
                    emailContent: '',//邮件内容
                    emailReceipt: 0,//是否回执 0-默认不回执，1-回执
                    emaileDelivery: 0,//投递状态  （紧急与非紧急） 0-默认常规，1-紧急
                    monocular: 0,//群发单显
                    emailTrack: 0,//0 - 不追踪  1 - 追踪
                    emailSendTiming: '', //邮件定时发送时间
                    senderEmail: '',//发件人邮箱
                    senderNickName: '',//发件人昵称
                    boxId: '',
                    emailOriginalId: ''
                },
                isTimeSend: false,//是否定时发送
                checkList: ['追踪邮件'],
                content: '',
                old: {},
                isLoading:false
            }
        },
        computed: {
            ...mapState(['common']),
            ...mapGetters(["userInfo"]),
        },
        watch: {
            checkList(val, old) {
                let el = this.getArrDifference(val, old);
                if (el[0] == '定时发送') {
                    if (!old.includes('定时发送')) {
                        this.$refs.dialogTargetTime.init();
                    } else {
                        this.form.emailSendTiming = '';
                    }
                }
            }
        },
        mounted() {
            this.bus.$on('getInfoWrite', params => {
                this.form = Object.assign({}, this.form, params);
                this.bus.$off('getInfoWrite');
                //判断是否改变
                if (this.form.senderEmail != '' && !this.common.isExpired) {
                    if (!this.isEqual()) {
                        this.$confirm(' <div style="margin: 20px 10px;">\n' +
                            '        <p style="line-height: 30px;\n' +
                            '        font-size: 14px;">您正在编辑内容，是否保存至草稿箱？</p>\n' +
                            '      </div>', '保存邮件到草稿箱', {
                            dangerouslyUseHTMLString: true,
                            closeOnClickModal: false,
                            closeOnPressEscape: false,
                            confirmButtonText: '保 存',
                            cancelButtonText: '取 消',
                        }).then(() => {
                            this.sendEmail(2)
                        }).catch(() => {
                        })
                    }
                }
            })
            const detail = JSON.parse(this.$route.query.row);
            this.content = detail;
            this.old = JSON.parse(this.$route.query.row);
            this.form.emailContent = detail.emailContent;
            this.form.emailOriginalId = detail.emailOriginalId;
            this.form.emailSubject = detail.emailSubject;
            this.form.addresseeEmail = dealStr(detail.addresseeEmail);
            this.form.emailCarbonCopy = dealStr(detail.emailCarbonCopy);
            this.form.emailSecretDelivery = dealStr(detail.emailSecretDelivery);
            this.form.emailHtmlpicList = detail.emailHtmlpicList;
            this.form.emailSendTiming = detail.emailSendTiming;
            this.form.emailReceipt = parseInt(detail.emailReceipt);
            this.form.emaileDelivery = parseInt(detail.emaileDelivery);
            this.form.emailTrack = detail.emailTrack;
            this.form.monocular = parseInt(detail.monocular);
            if (this.form.monocular == 1) this.checkList.push('群发单显');
            if (this.form.emailReceipt == 1) this.checkList.push('回执');
            if (this.form.emaileDelivery == 2) this.checkList.push('紧急');
            if (this.form.emailTrack == 1){
                this.checkList.push('追踪邮件')
            }else{
                this.checkList.splice(this.checkList.findIndex(item => item == '追踪邮件'), 1)
            }
            if (this.form.emailSendTiming) {//存在 - 不为空
                this.isTimeSend = true;
                this.checkList.push('定时发送');
            }
            this.form.senderEmail = detail.userEmail;
            if (detail.boxId == 0) {//收件箱
                this.form.senderNickName = this.userInfo.account;//获取用户名
            } else {
                this.form.senderNickName = detail.senderNickName;
            }
            //收件箱
            let sendMan;
            if (detail.emailType == 1) {//收件箱
                sendMan = detail.userEmail;
            } else {
                sendMan = detail.senderEmail;
            }
            let params = {
                senderEmail: sendMan,//发件人
                addresseeEmail: detail.addresseeEmail ? detail.addresseeEmail.split(",") : [],//收件人
                isCarbonCopy: this.form.emailCarbonCopy.length == 0 ? false : true,
                emailCarbonCopy: detail.emailCarbonCopy ? detail.emailCarbonCopy.split(",") : [],//抄送
                isSecretDelivery: (this.form.emailSecretDelivery.length == 0 || detail.boxId == 3) ? false : true,
                emailSecretDelivery: (detail.emailSecretDelivery && (detail.boxId == 3 || detail.boxId == 2)) ? detail.emailSecretDelivery.split(",") : [],//密送
                emailSubject: this.form.emailSubject,//主题
                monocular: this.form.monocular == 1 ? true : false
            }
            //初始化顶部组件
            this.$refs.write.init(params)
            //初始化编辑器
            this.$refs.makeBtn.init({
                emailContent: this.form.emailContent,
                emailHtmlpicList: this.form.emailHtmlpicList,
                monocular: this.form.monocular == 1 ? true : false
            });
        },
        methods: {
            //提交审批
            toApproval(params) {
                this.form.emailReceipt = this.form.emaileDelivery = this.form.emailTrack=0;
                this.checkList.map(item => {
                    if (item === '回执') {
                        this.form.emailReceipt = 1;
                    } else if (item === '紧急') {
                        this.form.emaileDelivery = 2;
                    } else if (item === '追踪邮件') {
                        this.form.emailTrack = 1;
                    }
                })
                this.form = Object.assign({}, this.form, params);
                if (this.getParams()) {
                    const target = JSON.parse(JSON.stringify(this.form));
                    this.$refs.dialogApproval.init(target);
                }
            },
            getParams() {
                if (this.form.senderEmail == '') {
                    this.$message({
                        duration: 1500,
                        message: '请选择发件人邮箱',
                        type: "success"
                    });
                    return false
                } else if (this.form.addresseeEmail.length === 0) {
                    this.$message({
                        duration: 1500,
                        message: '请输入收件人邮箱',
                        type: "success"
                    });
                    return false
                } else if (!this.form.emailSubject) {
                    this.$message({
                        duration: 1500,
                        message: '请输入主题',
                        type: "success"
                    });
                    return false
                } else if (!this.form.emailContent) {
                    this.$message({
                        duration: 1500,
                        message: '请输入邮件内容',
                        type: "success"
                    });
                    return false
                } else {
                    return true
                }
            },
            //取消按钮回调
            getCancel(params) {
                this.form = Object.assign({}, this.form, params);
                if (this.form.senderEmail != '' && !this.common.isExpired) {
                    if (!this.isEqual()) {
                        this.$confirm(' <div style="margin: 20px 10px;">\n' +
                            '        <p style="line-height: 30px;\n' +
                            '        font-size: 14px;">您正在编辑内容，是否保存至草稿箱？</p>\n' +
                            '      </div>', '保存邮件到草稿箱', {
                            dangerouslyUseHTMLString: true,
                            closeOnClickModal: false,
                            closeOnPressEscape: false,
                            confirmButtonText: '保 存',
                            cancelButtonText: '不保存',
                        }).then(() => {
                            this.sendEmail(this.form.sendType)
                            this.$router.go(-1);
                        }).catch(() => {
                            this.$router.go(-1);
                        })
                    } else {
                        this.$router.go(-1);
                    }
                } else {
                    this.$router.go(-1);
                }
            },
            isEqual() {
                if ((this.form.addresseeEmail == this.old.addresseeEmail)
                    && (this.form.emailSubject == this.old.emailSubject)
                    && (this.isEqualArray(this.form.emailHtmlpicList, this.old.emailHtmlpicList))) {
                    return true
                }
                return false
            },
            //预览
            review(params) {
                let info = Object.assign({}, this.form, params);
                let routeUrl = this.$router.resolve({
                    name: '/mail/write/Review',
                    query: {
                        info: JSON.stringify(info)
                    }
                });
                window.open(routeUrl.href, '_blank');
            },
            getInfoMake(params) {//文本编辑器数据 + 附件数据 emailContent emailHtmlpicList
                this.form = Object.assign({}, this.form, params)
            },
            getSendEmail(email) {
                this.form.senderEmail = email;
            },
            getInfoWrite(params) { //顶部数据 - 点击发送按钮触发
                this.form = Object.assign({}, this.form, params);
                this.sendEmail(params.sendType)
            },
            getRightTime(time) {//回调时间
                this.form.emailSendTiming = time;
                if (time == '') {
                    const index = this.checkList.indexOf("定时发送");
                    this.checkList.splice(index, 1);
                }
            },
            cancel() {
                this.$confirm('您正在写信，是否离开写信页面?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: "success"
                }).then(() => {
                    this.$router.go(-1)
                }).catch(() => {
                    return;
                });
            },
            //发送邮件
            sendEmail(type) {
                if (this.form.senderEmail == '') {
                    this.$message({
                        duration: 1500,
                        message: '请选择发件人邮箱',
                        type: "success"
                    });
                    return;
                }
                if (type != 2) {
                    if (!this.form.emailSubject) {
                        this.$message({
                            duration: 1500,
                            message: '请输入主题',
                            type: "success"
                        });
                        return;
                    } else if (this.form.addresseeEmail.length === 0) {
                        this.$message({
                            duration: 1500,
                            message: '请输入收件人邮箱',
                            type: "success"
                        });
                        return;
                    }
                }
                let msg = '';
                if (this.form.addresseeEmail.length > 30) {
                    msg = '收件人最多不超过30个！'
                }
                if (this.form.emailCarbonCopy.length > 20) {
                    msg = '抄送人最多不超过20个！'
                }
                if (this.form.emailSecretDelivery.length > 20) {
                    msg = '密送人最多不超过20个！'
                }
                if(msg){
                    this.$confirm(' <div style="margin: 20px 10px;">\n' +
                        '        <p style="line-height: 30px;font-size: 14px;">'+msg+'</p></div>', '提示', {
                        dangerouslyUseHTMLString: true,
                        closeOnClickModal: false,
                        closeOnPressEscape: false,
                        confirmButtonText: '确 定',
                    }).then(() => {
                        return;
                    }).catch(() => {
                        return;
                    })
                }
                //处理参数
                this.form.emailTrack=this.form.emailReceipt = this.form.emaileDelivery = 0;
                let state = true;
                this.checkList.map(item => {
                    if (item === '回执') {
                        this.form.emailReceipt = 1;
                    } else if (item === '紧急') {
                        this.form.emaileDelivery = 2;
                    } else if (item === '追踪邮件') {
                        this.form.emailTrack = 1;
                    } else if (item === '定时发送') {
                        if (this.form.emailSendTiming == '') {
                            state = false;
                            this.$message({
                                message: '请选择定时发送时间',
                                type: 'error'
                            });
                        }
                    }
                })
                if (!state) return;
                this.form.emailContent = encodeURIComponent(this.form.emailContent);
                this.form.boxId = type ? type : '';
                this.toSend();
            },
            toSend() {
                this.form = Object.assign({}, this.form, {temailInfoId: this.content.temailInfoId})
                const boxID = this.form.boxId;
                const monocular = this.form.monocular;
                const title = this.form.emailSubject;
                const emailSendTiming = this.form.emailSendTiming;
                this.isLoading=true
                sendEmail(this.form).then(res => {
                    this.isLoading=false;
                    if (res.data.success) {
                        this.reset();
                        if(boxID==2){//存草稿
                            this.$message({message: res.data.msg, type: 'success'});
                            this.$router.go(-1)
                        }else{
                            if (this.targetEmail) {
                                this.$emit('closeMail')
                            } else {
                                const params = JSON.stringify({
                                    id: res.data.data,
                                    title: title,
                                    monocular: monocular,
                                    emailSendTiming: emailSendTiming
                                })
                                //跳转 成功页面
                                this.$router.push({
                                    path:'/mail/success',
                                    query:{
                                        params: params
                                    }
                                });
                            }
                        }
                    } else {
                        this.form.emailContent = decodeURIComponent(this.form.emailContent);
                    }
                }).catch(err => {
                    this.isLoading=false;
                    this.form.emailContent = decodeURIComponent(this.form.emailContent);
                })
            },
            //重置数据
            reset() {
                this.$refs.write.init('')//重置顶部组件
                this.$refs.makeBtn.init('');//重置编辑器
                this.bus.$emit('refreshEmailNum')
                this.form = {
                    addresseeEmail: [],//收件人邮箱数组
                    emailCarbonCopy: [],//抄送数组
                    emailSecretDelivery: [],//密送数组
                    emailHtmlpicList: [],//附件列表
                    emailSubject: '',//主题
                    emailContent: '',//邮件内容
                    emailReceipt: 0,//是否回执 0-默认不回执，1-回执
                    emaileDelivery: 0,//投递状态  （紧急与非紧急） 0-默认常规，1-紧急
                    senderEmail: '',//发件人邮箱
                    senderNickName: this.userInfo.account,//发件人昵称,
                    boxId: ''
                }
                this.checkList = [];
            },
            getArrDifference(arr1, arr2) {
                return arr1.concat(arr2).filter(function (v, i, arr) {
                    return arr.indexOf(v) === arr.lastIndexOf(v);
                });
            },
            isEqualArray(obj1, obj2) {
                var o1 = obj1 instanceof Object;
                var o2 = obj2 instanceof Object;
                if (!o1 || !o2) {/*  判断不是对象  */
                    return obj1 === obj2;
                }

                if (Object.keys(obj1).length !== Object.keys(obj2).length) {
                    return false;
                    //Object.keys() 返回一个由对象的自身可枚举属性(key值)组成的数组,例如：数组返回下表：let arr = ["a", "b", "c"];console.log(Object.keys(arr))->0,1,2;
                }

                for (var attr in obj1) {
                    var t1 = obj1[attr] instanceof Object;
                    var t2 = obj2[attr] instanceof Object;
                    if (t1 && t2) {
                        return this.isEqualArray(obj1[attr], obj2[attr]);
                    } else if (obj1[attr] !== obj2[attr]) {
                        return false;
                    }
                }
                return true;
            }
        }
    }
</script>

<style lang="scss">
  $bgActiveColor: #E9F3FD;
  $fontColor: #2A97F9;
  $lineColor: #F3F3F3;
  .write {
    padding: 15px;
    margin: 0;
    border-radius: 10px;
    background-color: #fff;
    height: auto;

    .el-select.footSend {
      width: auto;
    }

    button.el-button.el-button--default {
      line-height: 30px;
      padding: 0 15px;

      i {
        margin-right: 5px;
      }
    }

    button.el-button.el-button--default.active {
      background-color: $bgActiveColor;
      color: $fontColor;
    }

    .edit {
      height: 450px;
      background-color: #F3F3F3;
    }

    .info {

      display: flex;
      align-items: center;
      margin-bottom: 10px;
      font-size: 14px;

      h1 {
        font-size: 15px;
        color: #1B2242;
        margin-right: 30px;
        padding: 0;
        font-weight: normal;
      }
    }

    .make-btn {
      margin-bottom: 50px;
    }
  }
</style>
